package com.kanshu.ksgb.fastread.doudou.module.makemoney.fragment;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseFragment;
import com.kanshu.ksgb.fastread.doudou.common.business.event.LoginEvent;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.PageRequestParams;
import com.kanshu.ksgb.fastread.doudou.common.share.ShareBean;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.SwipeRefreshHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.LetterSpacingTextView;
import com.kanshu.ksgb.fastread.doudou.common.view.scrolllayout.ScrollTextView;
import com.kanshu.ksgb.fastread.doudou.module.makemoney.bean.ApprenticeBean;
import com.kanshu.ksgb.fastread.doudou.module.makemoney.bean.InvitationBean;
import com.kanshu.ksgb.fastread.doudou.module.makemoney.presenter.MakeMoneyPresenter;
import com.kanshu.ksgb.fastread.doudou.module.makemoney.share.ShareDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by wcy on 18/5/28
 */

@SuppressLint("SetTextI18n")
public class ApprenticeFragment extends BaseFragment {
    @BindView(R.id.invite_code)
    LetterSpacingTextView mInviteCode;
    Unbinder unbinder;
    @BindView(R.id.gift_indicator)
    ImageView mGiftIndicator;
    @BindView(R.id.apprentice_num)
    TextView mApprenticeNum;
    @BindView(R.id.container)
    FrameLayout mContainer;
    @BindView(R.id.apprentice_indicator)
    ImageView mApprenticeIndicator;
    View mGiftExplainsLayout;
    View mApprenticeLayout;
    LinearLayout mLinearContainer;
    ShareBean mShareBean;
    MakeMoneyPresenter mPresenter;
    List<ApprenticeBean> mApprenticeBeans = new ArrayList<>();
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout mSwipeRefresh;
    @BindView(R.id.lamp_container)
    LinearLayout mLampContainer;
    @BindView(R.id.scroll_text)
    ScrollTextView mScrollText;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_apprentice_make_money_layout, null);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        init(view);
        loadData();
        return view;
    }

    private void init(View view) {
        mGiftExplainsLayout = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_gifts_explain_layout, null);
        mContainer.addView(mGiftExplainsLayout);
        SwipeRefreshHelper.init(mSwipeRefresh, this::getNums);
        view.findViewById(R.id.copy_invite_code).setOnLongClickListener(view1 -> {
            ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData myClip = ClipData.newPlainText("text", mInviteCode.getText().toString());
            assert cm != null;
            cm.setPrimaryClip(myClip);
            ToastUtil.showMessage("复制成功");
            return false;
        });
        mInviteCode.setSpacing(5f);
        mPresenter = new MakeMoneyPresenter(lifeCyclerSubject);
    }

    private void loadData(){
        mPresenter.getInvitationInfo(new INetCommCallback<InvitationBean>() {
            @Override
            public void onResponse(InvitationBean bean) {
                if (bean == null) {
                    return;
                }
                mInviteCode.setText(bean.invitation_code);
                mShareBean = bean.share;
                if (mShareBean != null) {
                    saveErcodeToSdcard(bean.share.qrcode);
                }
            }

            @Override
            public void onError(int code, String errDesc) {
            }
        });
        mPresenter.getNotifyList(new INetCommCallback<List<String>>() {
            @Override
            public void onResponse(List<String> strings) {
                if (!Utils.isEmptyList(strings)) {
                    mLampContainer.setVisibility(View.VISIBLE);
                    String lampStr = "";
                    for (String str : strings) {
                        lampStr += str + "               ";
                    }
                    mScrollText.setText(lampStr);
                } else {
                    mLampContainer.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(int code, String errDesc) {
                mLampContainer.setVisibility(View.GONE);
            }
        });
        getNums();
    }



    private void getNums() {
        PageRequestParams params = new PageRequestParams();
        params.num = 1000;
        mPresenter.getApprenticeList(params, new INetCommCallback<List<ApprenticeBean>>() {

            @Override
            public void onResponse(List<ApprenticeBean> list) {
                SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, null);
                if (Utils.isEmptyList(list)) {
                    mApprenticeBeans.clear();
                }else{
                    mApprenticeBeans = list;
                }
                mApprenticeNum.setText("我的徒弟" +  (mApprenticeBeans.size() == 0 ? "" :  "(" + list.size() + ")"));
                refreshApprentices(mApprenticeBeans);
            }

            @Override
            public void onError(int code, String errDesc) {
                SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, null);
            }
        });
    }

    private void refreshApprentices(List<ApprenticeBean> list) {
        if (mLinearContainer != null) {
            mLinearContainer.removeAllViews();
            if (!Utils.isEmptyList(list)) {
                for (ApprenticeBean bean : list) {
                    View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_apprentice_layout, null);
                    TextView tv1 = view.findViewById(R.id.nick_name);
                    TextView tv2 = view.findViewById(R.id.money);
                    TextView tv3 = view.findViewById(R.id.time);
                    tv1.setText(bean.nick_name);
                    tv2.setText((Integer.parseInt(bean.total_rmb) / 100) + "元");
                    tv3.setText(Utils.timeStampToDate(bean.reg_time_u, "yyyy.MM.dd"));
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    mLinearContainer.addView(view, params);
                }
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            getNums();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleLoginEvent(LoginEvent event) {
        loadData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R.id.share_view)
    public void onViewClicked() {
        ShareDialog.show(getActivity(), mShareBean);
        mScrollText.setMarqueeRepeatLimit(-1);
        mScrollText.setFocusableInTouchMode(true);
        mScrollText.setFocusable(true);
    }

    @OnClick({R.id.gift_explains, R.id.apprentice_indicator, R.id.apprentice_explains})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.gift_explains:
                DisplayUtils.visible(mGiftExplainsLayout, mGiftIndicator);
                DisplayUtils.gone(mApprenticeIndicator, mApprenticeLayout);
                break;
            case R.id.apprentice_explains:
                if (mApprenticeLayout == null) {
                    mApprenticeLayout = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_my_apprentice_layout, null);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    lp.setMargins(DisplayUtils.dip2px(mContext, 14), 0, DisplayUtils.dip2px(mContext, 14), 0);
                    mContainer.addView(mApprenticeLayout, lp);
                    mLinearContainer = mApprenticeLayout.findViewById(R.id.container);
                }
                if(mApprenticeLayout.getVisibility() == View.GONE){
                    getNums();
                }
                DisplayUtils.gone(mGiftExplainsLayout, mGiftIndicator);
                DisplayUtils.visible(mApprenticeIndicator, mApprenticeLayout);
                if (mLinearContainer.getChildCount() != mApprenticeBeans.size()) {
                    refreshApprentices(mApprenticeBeans);
                }
                break;
        }
    }

    /**
     * 保存二维码
     *
     * @param res
     */
    private void saveErcodeToSdcard(String res) {
        if (TextUtils.isEmpty(res)) {
            return;
        }
        File file = Utils.getDiskCacheDir(getActivity(), "ercode");
        if (!file.exists()) {
            file.mkdirs();
        }
        File fileTmp = new File(file, "ercode");
        if (!fileTmp.exists()) {
            try {
                fileTmp.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Bitmap bitmap = Utils.base64ToBitmap(res);
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(fileTmp));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }

}
